<template>
  <div id="app">
    <el-card shadow="always">

<!--条件查询语句-->
      <el-form :inline="true" size="medium"  :model="studentSearch" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="studentSearch.addr" placeholder="学生住址"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="studentSearch.cid" placeholder="所在班级">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="search" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" plain @click="addStudent" icon="el-icon-plus">添加学生</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" plain @click="handleDelete" icon="el-icon-remove">批量删除</el-button>
        </el-form-item>
      </el-form>

      <el-table
          :data="studentList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="学号"
            align="center"
            prop="sid"
            width="180"/>
        <el-table-column
            label="姓名"
            prop="sname"
            align="center"/>
        <el-table-column
            label="性别"
            prop="sex"
            align="center"/>
        <el-table-column
            label="年龄"
            prop="age"
            align="center"/>
        <el-table-column
            label="住址"
            prop="addr"
            align="center"/>
        <el-table-column
            label="所在班级"
            prop="cname"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页导航面版-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <!--编辑【添加|修改】学生对话框-->
    <el-dialog title="title" :visible.sync="dialogFormVisible">
      <el-form :model="student" :rules="rules" ref="ruleForm">
        <el-form-item label="学生姓名" prop="sname" :label-width="formLabelWidth">
          <el-input v-model="student.sname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生性别" prop="sex" :label-width="formLabelWidth">
          <el-radio v-model="student.sex" label="男">男</el-radio>
          <el-radio v-model="student.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="学生年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="student.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生住址" prop="addr" :label-width="formLabelWidth">
          <el-input v-model="student.addr" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在班级" prop="cid" :label-width="formLabelWidth">
          <el-select v-model="student.cid" placeholder="请选择所在班级">
            <el-option label="所在班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStudent">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import studentApi from "@/api/student"
import classesApi from "@/api/classes"
export default {
  data() {
    //年龄使用自定义校验规则
    let checkAge=(rule,value,callback)=>{
      if(value==='' || value==null){
        return callback(new Error('年龄不能为空'));
      }
      else if(!Number.isInteger(value)){
        return callback(new Error('年龄必须为数字值'));
      }
      else if(value<1 || value>150){
        return callback(new Error('年龄必须在0-150之间'));
      }else{
        callback();
      }
    }


    return {
      studentList: [],
      page:1,//当前页码
      pageSize:5,//每页显示记录条数
      total:11,//总记录数
      studentSearch:{},//查询条件对象
      classesList:[],//所有班级
      dialogFormVisible:false,//对话框显示状态，false不显示，true显示
      student:{},//代表添加或修改的学生对象
      title:'添加学生',//代表对话框标题
      formLabelWidth:'100px',//代表表单的标签宽度
      multipleSelection:[],//代表选中多选框的集合
      sids:[],//定义sid数组来存储选中的多选框的sid


      //定义校验规则
      rules: {
        //检验学生姓名
        sname: [
          { required: true, message: '请输入学生姓名', trigger: 'blur' },
        ],
        sex:[//检验学生性别
          {required:true,message:'请选择性别',trigger:'blur'}
        ],
        //检验学生年龄
        age:[
            //自定义规则来对年龄进行校验
          {validator:checkAge,trigger:'blur'}
          //{required:true,type:'number',message:'年龄必须为数字',trigger:'blur'},
        ],
        //学生住址
        addr:[
          {required:true,message:'请输入学生住址',trigger:'blur'}
        ],
        //学生所在班级
        cid:[
          {required:true,message:'请选择学生班级',trigger:'blur'}
        ]
      }
    }
  }
  ,
  created() {
    //this.findStudents()
    //this.findByPage(this.page,this.pageSize)
    this.findByPage();
    this.findAllClasses();

  },
  methods: {
    //1.查询所有学生
    async findStudents() {
      const {data:res} = await studentApi.findAllStudents()
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.list;
        //this.studentList = res.data.pr.rows;
      }
    },

    //2.分页查询
    async findByPage() {
      const {data:res} = await studentApi.findByPage(this.page,this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.studentList = res.data.pr.rows;
        this.total = res.data.pr.total;
      }
    },

    //3.查询所有班级

    async findAllClasses() {
      const {data:res} = await classesApi.findAllClasses()
      console.log(res)
      if (res.code === 200) {
        this.classesList = res.data.list;
      }
    },

    //4.条件查询带分页
   async search() {
      const {data:res} = await studentApi.search(this.page,this.pageSize,this.studentSearch);
      console.log(res);
      if (res.code === 200) {
        this.studentList = res.data.pr.rows;
        this.total = res.data.pr.total;
      }
    },

    //添加学生
    addStudent(){
      //修改对话框标题
      this.title='添加学生';
      //清空原来对话框中的学生数据
      this.student={};
      this.dialogFormVisible=true;//打开对话框
    },

    //保存学生
    saveStudent(){
      this.$refs.ruleForm.validate(async valid=>{
        //根据是否具有sid这个主键来判断是修改还是添加,有sid则是修改，没有就是添加
        let url="/student/add"//默认是添加学生
        let method = "post";//添加时候发送的是post请求
        if (this.student.sid){
          url="/student/update"//有值的话就是修改学生
          method="put";//修改时候发送的是put请求
        }//向后端发送请求
        if (valid){
          //studentApi.save(url,this.student)
          const {data:res} = await studentApi.save(url,method,this.student)
          console.log("res:",res);
          if (res.code === 200) {//执行成功返回200
            this.$message({
              type:'success',
              message:res.message,
              onClose:()=>{
                //关闭对话框时候，事件自动执行
                this.dialogFormVisible=false;
                //刷新页面
                //this.findStudents();
                //this.findByPage();
                this.search();
              }
            })
          }else{
            this.$message({//后端执行失败返回200
              type:'error',
              message:res.message
            })
          }
        }else{
          console.log("验证失败");
          return false;
        }
      })
    },


    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },

    handleSizeChange(val) {//当pagesize大小发生改变时触发
      this.pageSize=val;
      //this.findByPage();
      this.search();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {//当页码page发生改变时触发
      this.page=val;
      //this.findByPage();
      this.search();
      console.log(`当前页: ${val}`);
    },

    //编辑学生的方法
    handleEdit(index, row) {
      //在打开对话框之前修改对话框标题
      this.title='修改学生';
      //将学生信息数据显示到对话框当中
      this.student=row;
      this.dialogFormVisible=true;//先打开对话框

      console.log(index, row);
    },
    //单个删除或者批量删除学生都会触发
    handleDelete(index, row) {
      this.sids=[]
      if (row){
        this.sids.push(row.sids)
      }else{
        this.sids=this.multipleSelection.map(m=>m.sids)
      }
      this.$confirm(`是真的删学号为${this.sids}的学生吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {       // 当点击"确定"按钮后执行的操作
        let _this = this
        studentApi.deleteStudent(this.sids)
            .then(({data:res}) => {
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {// 数据重新加载
                    this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {     // 当点击"取消"按钮后执行操作
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    }
  }
}
</script>

<style>
#app{
  display: flex;
  justify-content: center;
}
.el-card{
  width: 90%;
}

.el-pagination{
  margin-top: 20px;
  text-align: right;
}

</style>








